<template>
	<div class="filter-box">
		<div class="filter-form" label-width="60px">
			<div v-for="item in dataList" :key="item.label" style="margin-bottom: 8px">
				<component
					style="width: 100%"
					:name="item.label"
					label-width="80px"
					hiddenIcon
					:initFocus="false"
					:arcoProps="{
						'checked-value': '1',
						'unchecked-value': '0',
						hiddenPre: true,
						hiddenNext: true
					}"
					v-model="item.value"
					v-model:fieldShow="item.fieldShow"
					:options="item.options"
					:prop="item.prop"
					:is="SelectInfo(showFieldList, item?.fieldType, 'component')"
					:fieldType="SelectInfo(showFieldList, item?.fieldType, 'fieldType')"
					@change="getSearch"
				></component>
			</div>
		</div>
		<div class="filter-btn">
			<a-button @click="handleBtn('submit')" type="primary">确定</a-button>
			<a-button @click="handleBtn('reset')">重置</a-button>
		</div>
	</div>
</template>
<script lang="ts" setup>
import { useShowFieldList } from "@/utils/field";
import mitt from "@/utils/bus";
const showFieldList = useShowFieldList();
import { isValid } from "@/utils";
import { SelectInfo } from "@/utils/index";

const props = defineProps({
	searchList: {
		type: Array as any,
		default: () => []
	},
	modelValue: {
		type: Object,
		default: () => ({})
	}
});
const emit = defineEmits(["handleSubmitFilter", "update:modelValue", "search"]);

const dataList: any = ref([]);
watch(
	() => props.searchList,
	(val) => {
		if (Array.isArray(val)) {
			val.forEach((i) => {
				i.filterIndex = i?.id || Math.random();
			});
		}
		dataList.value = val || [];
	},
	{ immediate: true }
);

const searchForm = () => {
	const arr = dataList.value.map((i) => {
		return {
			label: i.label,
			value: i.value,
			type: i.fieldType,
			options: i.options,
			filterIndex: i.filterIndex,
			fieldShow: i.fieldShow,
			queryType: i.queryType,
			filterType: "field"
		};
	});
	return arr;
};

mitt.on("delField", (data) => {
	const index = dataList.value.findIndex((i) => i.filterIndex === data);
	if (index !== -1) {
		dataList.value[index].value = "";
	}
	getSearch();
});

const getSearch = () => {
	const arr = searchForm();
	mitt.emit("fieldFilter", arr);
	const list = dataList.value.filter((i) => isValid(i.value));
	const data = list.map((i) => {
		return {
			key: i.id,
			value: i.value,
			queryType: i.queryType
		};
	});
	emit("update:modelValue", data);
	emit("search");
};

// 按钮操作
const handleBtn = (type) => {
	if (type === "reset") {
		dataList.value.map((item) => {
			return (item.value = "");
		});
		getSearch();
		emit("handleSubmitFilter", "reset");
	} else if (type === "submit") {
		getSearch();
	}
};
</script>
<style scoped lang="scss">
.filter-form {
	width: 400px;
	max-height: 600px;
	overflow: auto;
}
.filter-box {
	background-color: #fff;
	padding: 12px 0;
	box-shadow: rgba(99, 99, 99, 0.2) 0px 2px 8px 0px;
	border-radius: 6px;
	.filter-btn {
		text-align: center;
		margin-top: 12px;
	}
}
</style>
